var express = require('express');
var router = express.Router();
var User = require('../models/User');
var Category = require('../models/Category');
var Content = require('../models/Content');




router.use(function(req, res, next){
    if(!req.userInfo.isAdmin) {
        res.send('对不起，只有管理员才有权限进入后台管理');
        return;
    }
    next();
})

router.get('/',function(req , res, next){
    res.render('admin/index',{
        userInfo:req.userInfo
    });
})



router.get('/user',function(req,res) {

    var page = req.query.page || 1;
    var limit = 2;
    var skip = (page - 1) * limit;
    skip = Math.max(skip,0);
    var pages = 0;
    User.count().then(function(count) {

        //计算总页数
        var pages = Math.ceil( count / limit );
        //取值不能超过pages
        page = Math.min(page,pages);
        //取值不能小于1
        page = Math.min(page,1);
        User.find().sort({_id:-1}).limit(2).skip(skip).then(function(users) {
            res.render('admin/user_admin',{
                userInfo:req.userInfo,
                users:users,
                page:page,
                count:pages
            });
        });
    });
});


// router.get('/category',function(req,res) {
//     res.render('admin/category_index',{
//         userInfo:req.userInfo
//     });
// });


router.get('/category/add',function(req,res) {
    res.render('admin/category_add',{
        userInfo:req.userInfo
    });
});

router.post('/category/add',function(req,res) {
    var name = req.body.catename || '';

    if(name == '') {
        res.render('admin/error',{
            userInfo:req.userInfo,
            message:'名称不能为空'
        });
    }

    Category.findOne({
        name:name
    }).then(function(rs) {
        if(rs) {
            res.render('admin/error',{
                userInfo:req.userInfo,
                message:'分类已经存在了'
            });
            return Promise.reject();
        } else {
            //数据库不存在该分类
            return new Category({
                name:name
            }).save();
        }
    }).then(function(newCategory) {
        res.render('admin/success',{
            userInfo:req.userInfo,
            message:'分类保存成功',
            url:'admin/category'
        });
    });
});


router.get('/category',function(req,res) {


    var page = req.query.page || 1;
    var limit = 2;
    var skip = (page - 1) * limit;
    skip = Math.max(skip,0);
    var pages = 0;
    Category.count().then(function(count) {
        console.log(count);

        //计算总页数
        var pages = Math.ceil( count / limit );
        //取值不能超过pages
        page = Math.min(page,pages);
        //取值不能小于1
        page = Math.min(page,1);
        Category.find().limit(2).skip(skip).then(function(cates) {
            res.render('admin/category_index',{
                userInfo:req.userInfo,
                cates:cates,
                page:page,
                count:pages
            });
        });
    });
});


router.get('/category/edit',function(req,res) {
    var id = req.query.id || '';

    Category.findOne({
        _id:id
    }).then(function(category) {
        if(!category) {
            res.render('admin/error',{
                userInfo:req.userInfo,
                message:'分类信息不存在'
            });
        } else {
            res.render('admin/cate_edit',{
                userInfo:req.userInfo,
                category:category
            });
        }
    });
});

/*
*
*
* 如果form没有默认action的请求地址，就会请求道form所在的页面地址栏
* /admin/category/edit?id=59676c61d2a6d51f0cdf9c10
 */

router.post('/category/edit',function(req, res, next){
    
    var name = req.body.catename;
    var id = req.query.id;

    Category.findOne({
        _id:id
    }).then(function(cate){
        if(!cate){
            res.render('admin/error',{
                userInfo:req.userInfo,
                error:'该类不存在',
                url:'/admin/category'
            })
            return Promise.reject();
        }else{
            if(name === ''){
                res.render('admin/error',{
                    userInfo:req.userInfo,
                    error:'该命名不存在',
                    url:'/admin/category'
                })
                return Promise.reject();
            }else{
                if(name === cate.name){
                    res.render('admin/error',{
                        userInfo:req.userInfo,
                        error:'编辑成功',
                        url:'/admin/category'
                    })
                    return Promise.reject();
                }else{
                    return Category.findOne({
                        _id:{$ne:id},
                        name:name
                    });
                }
            }
        }
    }).then(function(hadCate){
        if(hadCate){
            res.render('admin/error',{
                userInfo:req.userInfo,
                error:'该类名已经存在',
                url:'/admin/category'
            })
            return Promise.reject();
        }else{
            return Category.update({
                _id:id
            },{
                name:name
            })
        }
    }).then(function(){
        res.render('admin/success',{
            userInfo:req.userInfo,
            message:'类名编辑成功',
            url:'/admin/category'
        })
    })
})


router.get('/category/delete',function(req, res, next){
    var id = req.query._id || '';
    console.log(id);
    Category.remove({
        _id:id
    }).then(function(data){
        res.render('admin/success',{
            userInfo:req.userInfo,
            message:'类名删除成功',
            url:'/admin/category'
        })
    });
});


router.get('/content/add',function(req,res) {

    Category.find().sort({_id:-1}).then(function(categories) {
        res.render('admin/content_add',{
            userInfo:req.userInfo,
            cates:categories
        });
    });
});

router.post('/content/add',function(req,res) {

    var category = req.body.category || 0;
    var title = req.body.title || '';
    var description = req.body.description || '';
    var content = req.body.content || '';

    if(category == '') {
        res.render('admin/error',{
            userInfo:req.userInfo,
            message:'内容分类不能为空'
        });
        return;
    }
    if(title == '') {
        res.render('admin/error',{
            userInfo:req.userInfo,
            message:'内容标题不能为空'
        });
        return;
    }

    return new Content({
        category:category,
        title:title,
        user:req.userInfo._id.toString(),
        description:description,
        content:content
    }).save().then(function(rs) {
        res.render('admin/success',{
            userInfo:req.userInfo,
            message:'保存成功'
        });
    });
});

router.get('/content',function(req,res) {
    var page = req.query.page || 1;
    var limit = 10;
    var skip = (page - 1) * limit;
    skip = Math.max(skip,0);
    var pages = 0;
    Content.count().then(function(count) {
        console.log(count);

        //计算总页数
        var pages = Math.ceil( count / limit );
        //取值不能超过pages
        page = Math.min(page,pages);
        //取值不能小于1
        page = Math.min(page,1);
        Content.find().limit(limit).skip(skip).populate(['category','user']).sort({
            addTime:-1
        }).then(function(contents) {
            console.log(contents);


            res.render('admin/content_index',{
                userInfo:req.userInfo,
                contents:contents,
                page:page,
                count:pages
            });
        });
    });
});

router.get('/content/edit',function(req,res) {
    var id = req.query.id || '';
    var categories = [];


    Content.findOne({
        _id:id
    }).then(function(contents) {
        if(!contents) {
            res.render('admin/error',{
                userInfo:req.userInfo,
                message:'分类信息不存在'
            });
            return Promise.reject();
        } else {
            return contents;
        }
    }).then(function(contents) {
        Category.find().sort({_id:-1}).then(function(cates) {
            res.render('admin/content_edit',{
                userInfo:req.userInfo,
                contents:contents,
                cates:cates
            });
        });
    });
});

//保存修改内容
router.post('/content/edit',function(req,res,next) {
    var id = req.query.id || '';

    var category = req.body.category || 0;
    var title = req.body.title || '';
    var description = req.body.description || '';
    var content = req.body.content || '';

    if(category == '') {
        res.render('admin/error',{
            userInfo:req.userInfo,
            message:'内容分类不能为空'
        });
        return;
    }
    if(title == '') {
        res.render('admin/error',{
            userInfo:req.userInfo,
            message:'内容标题不能为空'
        });
        return;
    }

    Content.update({
        _id:id
    },{
        category:category,
        title:title,
        description:description,
        content:content
    }).then(function() {
        res.render('admin/success',{
            userInfo:req.userInfo,
            message:'内容保存成功',
            url:'/admin/content/edit?id='+id
        });
    });

});

router.get('/content/delete',function(req,res) {
    var id = req.query.id || '';

    Content.remove({
        _id:id
    }).then(function(data){
        res.render('admin/success',{
            userInfo:req.userInfo,
            message:'内容删除成功',
            url:'/admin/content'
        })
    });
});

/*
*
*
* 如果form没有默认action的请求地址，就会请求道form所在的页面地址栏
* /admin/category/edit?id=59676c61d2a6d51f0cdf9c10
 */

// router.post('/category/edit',function(req, res, next){
    
//     var name = req.body.catename;
//     var id = req.query.id;

//     Category.findOne({
//         _id:id
//     }).then(function(cate){
//         if(!cate){
//             res.render('admin/error',{
//                 userInfo:req.userInfo,
//                 error:'该类不存在',
//                 url:'/admin/category'
//             })
//             return Promise.reject();
//         }else{
//             if(name === ''){
//                 res.render('admin/error',{
//                     userInfo:req.userInfo,
//                     error:'该命名不存在',
//                     url:'/admin/category'
//                 })
//                 return Promise.reject();
//             }else{
//                 if(name === cate.name){
//                     res.render('admin/error',{
//                         userInfo:req.userInfo,
//                         error:'编辑成功',
//                         url:'/admin/category'
//                     })
//                     return Promise.reject();
//                 }else{
//                     return Category.findOne({
//                         _id:{$ne:id},
//                         name:name
//                     });
//                 }
//             }
//         }
//     }).then(function(hadCate){
//         if(hadCate){
//             res.render('admin/error',{
//                 userInfo:req.userInfo,
//                 error:'该类名已经存在',
//                 url:'/admin/category'
//             })
//             return Promise.reject();
//         }else{
//             return Category.update({
//                 _id:id
//             },{
//                 name:name
//             })
//         }
//     }).then(function(){
//         res.render('admin/success',{
//             userInfo:req.userInfo,
//             message:'类名编辑成功',
//             url:'/admin/category'
//         })
//     })
// })























module.exports = router;